import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon, AtDrawer} from 'taro-ui';
import {View, Block, Image, Picker, Text} from '@tarojs/components'
import {vcmonitor} from "../../../utils/tools";
import Screen from "../../components/screen/screen";
import {
  MARKETPERFORMANCE_APP_LIST,
  MARKETPERFORMANCE_APP_SUMDATA,
  MARKETPERFORMANCE_APP_ALL_SITE,
  MARKETPERFORMANCE_APP_ALL_BD, TARO_ENV
} from '../../../constants/api'
import {user} from "../../../utils/user.service";
import {http} from "../../../utils/http";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import Water from "../../components/water-mark/index";
import './index.scss'

type PageOwnProps = {};
type PageState = {
  tipsNum: number
  listData: any
  drawerShow: boolean
  options: any
  formData: object
  sumData: object
}

class Index extends Component {
  state: PageState = {
    tipsNum: 0,
    listData: [],
    drawerShow: false,
    options: [
      {
        title: '站点',
        type: 'tag',
        key: 'tag',
        active: 0,
        data: []
      },
      {
        title: '市场人员姓名',
        type: 'tag',
        key: 'bn_id',
        active: 0,
        data: []
      },
      {
        title: '商品名称',
        type: 'input',
        placeholder: '请输入要搜索的商品名称',
        key: 'product_name'
      }
    ],
    formData: {
      page: 1,
      pageSize: 10,
      start_date: '',
      end_date: '',
      sid: '',
      goods_name: '',
      bduser_id: '',
      flag: true,
      from: 'mobile'
    },
    sumData: {
      all_total_fee: 0,
      all_gross_profit: 0,
      all_gross_profit_rate: 0,
      all_buy_amount: 0
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const siteRes = await http.HGet(MARKETPERFORMANCE_APP_ALL_SITE, this.state.formData)
    if (siteRes) {
      const {options} = this.state
      options[0].data = siteRes.data
      this.setState({
        options
      })
    }
    const bdRes = await http.HGet(MARKETPERFORMANCE_APP_ALL_BD, this.state.formData)
    if (bdRes) {
      const {options} = this.state
      options[1].data = bdRes.data
      this.setState({
        options
      })
    }
    this.getData()
  }

  total

  async onReachBottom() {
    const {formData} = this.state
    if (formData['page'] * 10 < this.total) {
      formData['page'] = formData['page'] + 1
      this.setState({formData}, async () => {
        this.getData()
      })
    }
  }

  async getData() {
    try{
      const formData = this.state.formData
      await Taro.showLoading({title: '加载中...'})
      const infoRes = await http.HGet(MARKETPERFORMANCE_APP_SUMDATA, formData)
      // infoRes.data[0]['all_buy_amount'] = infoRes['allData']['all_buy_amount']
      const sumData = {
        all_total_fee: infoRes['allData']['all_total_fee'] || 0,
        all_gross_profit: infoRes['allData']['all_gross_profit'] || 0,
        all_gross_profit_rate: infoRes['allData']['all_gross_profit_rate'] || 0,
        all_buy_amount: infoRes['allData']['all_buy_amount'] || 0
      }
      if (infoRes && JSON.stringify(infoRes) !== '{}' && infoRes.data) {
        this.setState({
          sumData
        })
      }
      const res = await http.HGet(MARKETPERFORMANCE_APP_LIST, formData)
      Taro.hideLoading()
      if (res && JSON.stringify(res) !== '{}') {
        this.total = res.totalRows
        if (formData.page === 1) {
          this.setState({
            listData: res.data
          })
        } else {
          this.setState({
            listData: [...this.state.listData, ...res.data]
          })
        }
      }
    } catch (e) {
      Taro.hideLoading()
    }
  }

  // 开始时间
  changeStart(date) {
    const formData: any = this.state.formData;
    const options = this.state.options;
    formData.start_date = date;

    // 筛选数据返回
    this.setState({
      formData,
      options
    });
    this.getData()
  }

  // 结束时间
  changeEnd(date) {
    const formData: any = this.state.formData;
    const options = this.state.options;
    formData.end_date = date;

    // 筛选数据返回
    this.setState({
      formData,
      options
    });
    this.getData()
  }

  // 截取名称
  getName(name = '') {
    if (name) {
      return name.length < 31 ? name : name.substr(0, 31) + '...';
    }
    return ''
  }

  // 关闭筛选
  setDrawer(drawerShow) {
    this.setState({
      drawerShow
    });
  }

  showTips(num) {
    const that = this
    that.setState({tipsNum: num}, () => {
      const timer = setTimeout(() => {
        that.setState({
          tipsNum: 0
        })
        clearTimeout(timer)
      }, 2100)
    })
  }

  // 监听抽屉返回数据
  screenChange(v, k, i) {
    const formData: any = this.state.formData;
    formData.page = 1
    const options = this.state.options;
    if (k === 'tag') {
      formData.sid = v;
    }
    if (k === 'bn_id') {
      formData.bduser_id = v;
    }
    if (k === 'product_name') {
      formData.goods_name = v;
    }
    /*if(k === 'seller_name'){
    }*/
    if (k == 'tag') {
      options[i].active = v;
    }
    if (k == 'bn_id') {
      options[i].active = v;
    }
    // 筛选数据返回
    this.setState({
      formData,
      options
    });
    this.getData()
  }

  render() {
    const {
      listData,
      drawerShow,
      options,
      sumData,
      tipsNum,
      formData
    }: any = this.state;
    return (
      <View className='vedrifcation'>
        <GzhAuth />
        <Water />
        <View className={`t-a-l flex h-lh while ${TARO_ENV + 'white'}`}>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeStart(value)
            }
            value={formData.start_date}
            style='width: 50%;'
          >
            <View className='t-a-c w-100 p-r-0 f-24'
              style={`color:${formData.start_date ? '#000' : '#c5c5c5'};`}
            >
              {formData.start_date || '选择使用时间'}
            </View>
          </Picker>
          <Text style='margin: 0 20px;'>至</Text>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeEnd(value)
            }
            value={formData.end_date}
            style='width: 50%;'
          >
            <View className='t-a-c w-100 p-r-0 f-24'
              style={`color:${formData.end_date ? '#000' : '#c5c5c5'};`}
            >
              {formData.end_date || '选择使用时间'}
            </View>
          </Picker>
        </View>
        <View className='m-tb-20 t-a-r p-r-30'>
          <AtIcon size='12' customStyle='vertical-align: inherit;' value='icon icon-shaixuan-01' className='m-r-10' />
          <Text className='select-text' onClick={() => this.setDrawer(true)}>
            筛选
          </Text>
        </View>
        <View className='top-info'>
          <View className='top-info-list'>
            <View className='title'>
              销售总额<View onClick={this.showTips.bind(this, 1)} className='aticon'> <AtIcon value='help' size='11'
                color='#bfbfbf'
              /></View>
            </View>
            <View className='num m-l-2'>
              <Text className='money'>￥</Text>
              {sumData.all_total_fee}
              <View className={`tips ${tipsNum == 1 ? 'twos' : ''}`}>销售总额:所有商品的销售总金额</View>
            </View>
          </View>
          <View className='top-info-list'>
            <View className='title'>
              总毛利润<View onClick={this.showTips.bind(this, 2)} className='aticon'><AtIcon value='help' size='11'
                color='#bfbfbf'
              /></View>
            </View>
            <View className='num m-l-2'>
              <Text className='money'>￥</Text>
              {sumData.all_gross_profit}
              <View className={`tips ${tipsNum == 2 ? 'twos' : ''}`}>毛利润: 所有商品的毛利润总额(毛利润等于商品销售金额减去成本价金额)</View>
            </View>
          </View>

          <View className='top-info-list'>
            <View className='title'>
              毛利率<View onClick={this.showTips.bind(this, 3)} className='aticon'><AtIcon value='help' size='11'
                color='#bfbfbf'
              /></View>
            </View>
            <View className='num'>
              {sumData.all_gross_profit_rate} %
              <View className={`tips ${tipsNum == 3 ? 'twos' : ''}`}>毛利率=（售价减去成本)除以售价乘以100%</View>
            </View>
          </View>

          <View className='top-info-list'>
            <View className='title'>
              销售量<View className='aticon' style='visibility: hidden'><AtIcon value='help' size='11' color='#bfbfbf'  /></View>
            </View>
            <View className='num'>
              {sumData.all_buy_amount}
            </View>
          </View>

        </View>
        <View className='list'>
          {
            listData.map(item => {
              return (
                <Block key={item.id}>
                  <View className='list-item'>
                    <View className='list-item-header'>
                      <View className='list-item-header-left'>
                        <View className='list-item-header-left-image'>
                          <Image src={item.goods_img} style='width: 100%;height: 100% !important;' />
                        </View>
                      </View>
                      <View className='list-item-header-right'>
                        <View className='list-item-header-right-name'>
                          {this.getName(item.product_name)}
                        </View>
                        <View className='list-item-header-right-index'>
                          编号：{item.goods_no}
                        </View>
                      </View>
                    </View>
                    <View className='sale'>
                      <View className='w-45'>
                        <View className='sale-title'>
                          销售总额
                        </View>
                        <View className='sale-content'>
                          <Text className='money'>￥</Text>
                          {item.total_fee}
                        </View>
                      </View>
                      <View className='w-45'>
                        <View className='sale-title'>
                          总毛利润
                        </View>
                        <View className='sale-content'>
                          <Text className='money'>￥</Text>
                          {item.gross_profit}
                        </View>
                      </View>
                      <View className='w-45'>
                        <View className='sale-title'>
                          毛利率
                        </View>
                        <View className='sale-content'>
                          {item.gross_profit_rate}%
                        </View>
                      </View>
                      <View className='w-45'>
                        <View className='sale-title'>
                          销售量
                        </View>
                        <View className='sale-content'>
                          {item.all_buy_amount}
                        </View>
                      </View>
                    </View>
                  </View>
                </Block>
              )
            })
          }
        </View>
        <AtDrawer
          show={drawerShow}
          mask
          onClose={this.setDrawer.bind(this, false)}
          right
        >
          <Screen
            options={options}
            onChange={this.screenChange.bind(this)}
          />
        </AtDrawer>
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
